package com.ujs.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujs.commonutils.constant.R;
import com.ujs.eduservice.entity.EduVideo;
import com.ujs.eduservice.feign.VodFeignService;
import com.ujs.eduservice.mapper.EduVideoMapper;
import com.ujs.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ujs.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-08-07
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Qualifier("com.ujs.eduservice.feign.VodFeignService")
    @Autowired
    private VodFeignService vodFeignService;

    @Override
    public void removeVideoByCourseId(String courseId) {
        try {
            QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id", courseId);
            wrapper.select("video_source_id");
            // 根据courseId查询所有的videoId
            List<EduVideo> eduVideos = baseMapper.selectList(wrapper);
            List<String> videoIdList = eduVideos.stream()
                    .filter(eduVideo -> !StringUtils.isEmpty(eduVideo.getVideoSourceId()))
                    .map(EduVideo::getVideoSourceId).collect(Collectors.toList());
            // 删除对应的视频文件
            if (videoIdList.size() > 0) {
                vodFeignService.deleteBatch(videoIdList);
            }
            // 删除小节
            QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<EduVideo>().eq("course_id", courseId);
            baseMapper.delete(queryWrapper);
        } catch (Exception e) {
            throw new GuliException(20001, "删除小节失败");
        }
    }

    @Override
    public void removeVideoAndAlyVideo(String videoId) {
        // 1.通过videoId，查询出阿里云的视频id
        EduVideo video = baseMapper.selectById(videoId);
        // 2.先删除阿里云中的视频，判断是否有视频id
        if (!StringUtils.isEmpty(video.getVideoSourceId())) {
            R r = vodFeignService.deleteAlyVideo(video.getVideoSourceId());
            if (r.getCode() == 20000) { // 成功
                // 3.再删除数据库中的记录
                baseMapper.deleteById(videoId);
            } else {
                throw new GuliException(20001, r.getMessage());
            }
        }
    }
}
